//
//  UILabel+Copyable.m
//  UILabel+Copyable
//
//  Created by sichenwang on 16/2/18.
//  Copyright © 2016年 sichenwang. All rights reserved.
//

#import "UILabel+Copyable.h"
#import <objc/runtime.h>

@interface UILabel ()


@end

@implementation UILabel (Copyable)


- (void)awakeFromNib{
    [super awakeFromNib];
    
    [self attachLongTapHandle];
}

- (instancetype)init {
    if (self = [super init]) {
        [self attachLongTapHandle];
    }
    return self;
}

- (void)attachLongTapHandle {
    self.userInteractionEnabled = YES;
    UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(actionS:)];
    [self addGestureRecognizer:longPress];
}

- (void)actionS:(UILongPressGestureRecognizer *)gesture{

    if (gesture.state == UIGestureRecognizerStateBegan) {

        [self becomeFirstResponder];
        // UILabel成为第一响应者
        [self becomeFirstResponder];
        UIMenuController * menuvc = [UIMenuController sharedMenuController];

        UIMenuItem * menuItem1 = [[UIMenuItem alloc] initWithTitle:[[MWConfigManager manager] objectForKey:@"copy" defaultValue:@"复制"] action:@selector(firstItemAction:)];
        menuvc.menuItems = @[menuItem1];
        [menuvc setTargetRect:self.frame inView:self.superview];
        [menuvc setMenuVisible:YES animated:YES];
   }
}

- (void)firstItemAction:(UIMenuItem *)item {

    //通过系统的粘贴板，记录下需要传递的数据

    UIPasteboard *pboard = [UIPasteboard generalPasteboard];

    pboard.string = self.text;

}

- (BOOL)canBecomeFirstResponder {
    return YES;
}

- (BOOL)canPerformAction:(SEL)action withSender:(id)sender {
    if (action == @selector(copy:)) {
        return YES;
    }
    return NO;
}

- (void)copy:(id)sender {
    UIPasteboard *pboard = [UIPasteboard generalPasteboard];
    pboard.string = self.text;
}

@end
